package com.net.orders.service.impl;

import com.caikun.model.common.PageResult;
import com.caikun.model.common.Result;
import com.caikun.model.dto.OrderPageDTO;
import com.caikun.model.dto.OrderSubmitDTO;
import com.caikun.model.dto.SpaceStatusDTO;
import com.caikun.model.entity.*;
import com.caikun.model.entity.OrderServiceDetail;
import com.caikun.model.vo.OrderTimeVo;
import com.caikun.model.vo.OrderVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.net.orders.fegin.OrderShoppingCarFegin;
import com.net.orders.fegin.OrderSpaceFegin;
import com.net.orders.fegin.OrderUserFegin;
import com.net.orders.mapper.OrderMapper;
import com.net.orders.mapper.OrderServiceMapper;
import com.net.orders.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单表(Order)表服务实现类
 *
 * @author makejava
 * @since 2025-07-17 08:53:21
 */
@Slf4j
@Service("orderService")
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderServiceMapper orderServiceMapper;

    @Autowired
    private OrderUserFegin orderUserFegin;

    @Autowired
    private OrderShoppingCarFegin orderShoppingCarFegin;

    @Autowired
    private OrderSpaceFegin orderSpaceFegin;

    /**
     * 通过ID查询单条数据
     *
     * @param orderId 主键
     * @return 实例对象
     */
    @Override
    public OrderVo queryById(Integer orderId) {
        Order order = orderMapper.queryById(orderId);
        User user = orderUserFegin.getUserInfo(order.getUserId()).getData();
        OrderVo orderVo = new OrderVo();
        // 拷贝字段（order->orderVo）
        BeanUtils.copyProperties(order, orderVo);
        // 拷贝字段（user->orderVo）
        BeanUtils.copyProperties(user, orderVo);
        return orderVo;
    }

    /**
     * 通过用户ID查询所属订单数据
     *
     * @param userId 用户ID
     * @return 实例对象列表
     */
    public List<OrderVo> queryByUserId(Integer userId) {
        User user = orderUserFegin.getUserInfo(userId).getData();
        List<Integer> userIds = new ArrayList<>();
        userIds.add(userId);
        OrderPageDTO orderPageDTO = new OrderPageDTO();
        List<Order> orders = orderMapper.queryAllByPage(userIds, orderPageDTO);
        // 封装返回模型
        List<OrderVo> orderVos = new ArrayList<>();
        for (Order order : orders) {
            OrderVo vo = new OrderVo();
            BeanUtils.copyProperties(order, vo);
            BeanUtils.copyProperties(user, vo);
            orderVos.add(vo);
        }
        return orderVos;
    }

    /**
     * 获取用户正在使用的订单
     *
     * @param userId 用户ID
     * @return 订单对象
     */
    @Override
    public OrderTimeVo getUserOrderByStatus(Integer userId) {
        List<OrderVo> orders = queryByUserId(userId);
        for (OrderVo orderVo : orders) {
            if(orderVo.getOrderStatus() == 0){  // 0 : 正在使用  1 : 已完成
                OrderTimeVo vo = new OrderTimeVo();
                // 拷贝字段（orderVo->vo）
                BeanUtils.copyProperties(orderVo, vo);
                Long time = calulateRemainingTime(vo);
                vo.setRemainingTime(time);
                return vo;
            }
        }
        return null;
    }

    /**
     * 计算订单剩余时间
     *
     * @param vo 订单对象
     * @return 剩余时间（秒）
     */
    private Long calulateRemainingTime(OrderTimeVo vo) {
        //获取开始时间
        Long startTime = vo.getStartTime().getTime();
        //获取使用的总时长
        Space data = orderSpaceFegin.queryById(vo.getSpaceId()).getData();
        Long useTime = Long.valueOf(data.getUseTime()); // 当前单位为分钟
        useTime *= 60 * 1000;

        Long currentTime = new Date().getTime();
        Long remainTime = startTime + useTime - currentTime;

        log.info("订单剩余时间(分钟)：{}", remainTime / 1000L / 60L);

        return Math.max(0L, remainTime / 1000L);
    }

    /**
     * 设置订单结束时间
     *
     * @param orderId  订单ID
     *
     * @return 是否成功
     */
    @Override
    public Boolean setOverTime(Integer orderId) {

        Order order1 = orderMapper.queryById(orderId);
        orderSpaceFegin.setStatus(new SpaceStatusDTO(order1.getSpaceId(), 0)); // 设置车位状态为空闲

        Order order = new Order();
        order.setOrderId(orderId);
        order.setOrderStatus(2);
        order.setOverTime(new Date());
        return orderMapper.update(order) > 0;
    }

    /**
     * 设置订单状态
     *
     * @param orderId  订单ID
     * @param status   订单状态
     * @return 是否成功
     */
    @Override
    public Boolean setOrderStatus(Integer orderId, Integer status) {
        Order order = new Order();
        order.setOrderId(orderId);
        order.setOrderStatus(status);
        return orderMapper.update(order) > 0;
    }


    /**
     * 根据用户条件分页查询
     *
     * @param orderPageDTO 筛选条件
     * @param pageNum      当前页
     * @param pageSize     每页大小
     * @return 查询结果
     */
    @Override
    public PageResult<OrderVo> queryByPage(OrderPageDTO orderPageDTO, int pageNum, int pageSize) {
        User user1 = new User();
        user1.setUsername(orderPageDTO.getUsername());
        user1.setRealName(orderPageDTO.getRealName());
        // 去用户微服务查询用户信息
        List<User> users = orderUserFegin.queryByCondition(user1).getData();

        // 构建userId到User对象的映射
        Map<Integer, User> userMap = users.stream()
                .filter(Objects::nonNull)  // 过滤掉null的User对象
                .filter(user -> user.getUserId() != null)  // 过滤掉userId为null的用户
                .collect(Collectors.toMap(
                        User::getUserId,  // 键是userId
                        user -> user,     // 值就是User对象本身
                        (existing, replacement) -> existing  // 如果有重复userId，保留已存在的User
                ));

        List<Integer> userIds = users.stream()
                .map(User::getUserId)
                .filter(Objects::nonNull)
                .toList();

        /**
         * PageHelper.startPage(pageNum, pageSize) 必须在 查询数据库之前调用，
         * 它通过拦截下一条 SQL 查询并自动加上 LIMIT 来实现物理分页。
         */
        PageHelper.startPage(pageNum, pageSize); // 开启分页
        // TODO :为了方便调试，在用户查询失败时，直接返回空
        if (userIds.isEmpty()) {
            return null;
        }
        List<Order> orders = orderMapper.queryAllByPage(userIds, orderPageDTO);
        PageInfo<Order> pageInfo = PageInfo.of(orders);

        // 封装返回模型
        List<OrderVo> orderVos = new ArrayList<>();
        for (Order order : orders) {
            OrderVo vo = new OrderVo();
            BeanUtils.copyProperties(order, vo);
            BeanUtils.copyProperties(userMap.get(order.getUserId()), vo);
            orderVos.add(vo);
        }

        PageResult<OrderVo> pageResult = PageResult.of(orderVos, pageInfo);

        log.info("查询结果---：{}", pageResult);

        return pageResult;
    }


    /**
     * 新增数据
     *
     * @param order 实例对象
     * @return 实例对象
     */
    @Override
    public Order insert(Order order) {
        this.orderMapper.insert(order);
        return order;
    }

    /**
     * 修改数据
     *
     * @param order 实例对象
     * @return 实例对象
     */
    @Override
    public Order update(Order order) {
        this.orderMapper.update(order);
        return orderMapper.queryById(order.getOrderId());
    }

    /**
     * 通过主键删除数据
     *
     * @param orderId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer orderId) {
        return this.orderMapper.deleteById(orderId) > 0;
    }

    /**
     * 提交订单（从购物车获取订单服务详情）
     *
     * @param orderSubmitDTO 提交订单参数
     * @return 订单信息
     */
    @Override
    public Map<String, Object> submit(OrderSubmitDTO orderSubmitDTO) {
        Order order = new Order();
        // 拷贝字段（orderSubmitDTO->order）
        BeanUtils.copyProperties(orderSubmitDTO, order);
        order.setStartTime(new Date());
        order.setOrderStatus(0);
        order.setPayType("微信支付");
        order.setIsDelete(0);
        // 插入订单
        int row = orderMapper.insert(order);
        // 检验订单是否创建成功
        if (row < 1) {
            return null;
        }

        // 获取自动生成的订单ID
        Integer orderId = order.getOrderId();

        // 获取用户购物车数据
        List<ShoppingCar> shoppingCars = orderShoppingCarFegin.getshoppingCar(orderSubmitDTO.getUserId()).getData();
        for (ShoppingCar shoppingCar : shoppingCars) {
            OrderServiceDetail orderServiceDetail = new OrderServiceDetail();
            orderServiceDetail.setOrderId(orderId);
            log.info("购物车数据---：{}", shoppingCar);
            // 拷贝字段（shoppingCar->orderServiceDetail）
            BeanUtils.copyProperties(shoppingCar, orderServiceDetail);
            orderServiceDetail.setIsDelete(0);
            // 插入订单服务详情
            row = orderServiceMapper.insert(orderServiceDetail);
            if (row < 1) {
                return null;
            }
        }

        // 删除用户购物车数据
        orderShoppingCarFegin.deleteByUserId(orderSubmitDTO.getUserId());

        // 修改车位状态
        SpaceStatusDTO spaceStatusDTO = new SpaceStatusDTO();
        spaceStatusDTO.setId(orderSubmitDTO.getSpaceId());
        // 设置车位状态  0-空闲中 1-忙碌中 2-维修中
        spaceStatusDTO.setStatus(1);
        orderSpaceFegin.setStatus(spaceStatusDTO);

        Map<String, Object> result = new HashMap<>();
        result.put("orderId", orderId);
        return result;
    }
}
